<template>
  <div class="custom-table">
    <!-- 表头 -->
    <div class="table-header">
      <div
        v-for="column in props.columns"
        :key="column.key"
        class="header-cell"
        :style="{
          width: column.flex ? undefined : column.width,
          flex: column.flex ? 1 : undefined,
          textAlign: column.align || 'left',
        }"
      >
        {{ column.label }}
      </div>
    </div>

    <!-- 表格数据行 -->
    <div
      v-for="(row, index) in displayTableData"
      :key="row.examId"
      class="table-row-container"
      :class="{ 'add-row': row.isNew }"
    >
      <div class="table-row" :class="{ 'add-row': row.isNew }">
        <div
          v-for="column in props.columns"
          :key="column.key"
          class="table-cell"
          :style="getColumnStyle(column)"
        >
          <!-- 序号列 -->
          <template v-if="column.key === 'index'">
            {{ row.isNew ? '' : index + 1 }}
          </template>

          <!-- 项目列 -->
          <template v-else-if="column.key === 'drugName'">
            <span>{{ row.drugName }}{{ row.specification }}</span>
          </template>

          <!-- 皮试列 -->
          <template v-else-if="column.key === 'skinTest'">
            <el-select
              v-model="row.skinTest"
              filterable
              style="width: 60px"
              class="borderless-select"
              placeholder=""
              suffix-icon=""
              @change="updateRow(row, index)"
              v-if="visitStatus == '1'"
            >
              <el-option
                v-for="frequency in skinTestEnum"
                :key="frequency.text"
                :label="frequency.text"
                :value="frequency.value"
              />
            </el-select>
            <span v-else>{{ row.skinTest }}</span>
          </template>
          <!-- 类型列 -->
          <template v-else-if="column.key === 'drugCategory'">
            {{ row.drugCategoryName }}
          </template>

          <!-- 周期列 -->
          <template v-else-if="column.key === 'period'">
            <div
              style="
                display: flex;
                align-items: center;
                gap: 8px;
                position: relative;
              "
            >
              <el-input-number
                v-model="row.dosage"
                :min="0"
                :max="999"
                :step="0.1"
                :controls="false"
                class="borderless-input"
                style="width: 50px"
                @change="updateRow(row, index)"
                @focus="showKeyboard(row, index, 'dosage')"
                @click.stop
                v-if="visitStatus == '1'"
              />
              <span v-else>{{ row.dosage }}</span>
              <span>{{ row.minPackUnitText }}</span>

              <!-- 数字键盘 -->
              <div
                v-if="
                  keyboardVisible &&
                  currentEditRow === row &&
                  currentEditField === 'dosage'
                "
                @click.stop
              >
                <NumberDecimal @input="inputNumber" @delete="deleteNumber" />
              </div>
            </div>
          </template>

          <!-- 总量列 -->
          <template v-else-if="column.key === 'totalCount'">
            <div
              style="
                display: flex;
                align-items: center;
                gap: 4px;
                position: relative;
              "
            >
              <el-input-number
                v-model="row.totalOutQty"
                :min="0"
                :max="999"
                :controls="false"
                class="borderless-input"
                ref="searchInputRef"
                style="width: 50px"
                @change="updateRow(row, index)"
                @focus="showKeyboard(row, index, 'totalOutQty')"
                @click.stop
                v-if="visitStatus == '1'"
              />
              <span v-else>{{ row.totalOutQty }}</span>
              <span v-if="row.isSplit == '1'">{{ row.minPackUnitText }}</span>
              <span v-else>{{ row.totalOutQtyUnitText }}</span>

              <!-- 总量数字键盘 -->
              <div
                v-if="
                  keyboardVisible &&
                  currentEditRow === row &&
                  currentEditField === 'totalOutQty'
                "
                @click.stop
              >
                <NumericKeyboardInt
                  @input="inputNumber"
                  @delete="deleteNumber"
                />
              </div>
            </div>
          </template>

          <!-- 备注列 -->
          <template v-else-if="column.key === 'remark'">
            <AutocompleteMulti
              v-model="row.remark"
              class="borderless-select right-select"
              placeholder=""
              style="width: calc(100% - 30px)"
              :trigger-on-focus="true"
              :fetch-suggestions="querySearchAsync"
              :selected-color="'#16ada4'"
              @change="(value) => onchangeAutocom(row, index, value)"
              v-if="visitStatus == '1'"
            />
            <span v-else>{{ row.remark }}</span>
          </template>

          <!-- 自定义列 -->
          <template v-else>
            {{ row[column.key as keyof any] }}
          </template>
        </div>
      </div>

      <!-- 悬浮删除按钮 -->
      <div
        class="delete-button"
        @click="deleteRow(row, index)"
        v-if="visitStatus == '1'"
      >
        <img src="@/assets/manage/icon_off_hover.svg" alt="删除" />
      </div>
    </div>
    <!-- 搜索行 -->
    <div class="table-row search-row" v-if="visitStatus == '1'">
      <div
        v-for="(column, columnIndex) in props.columns"
        :key="`search-${column.key}`"
        class="table-cell"
        :style="{
          border: columnIndex === 0 ? 'none' : undefined,
          position: columnIndex === 0 ? 'relative' : undefined,
        }"
      >
        <template v-if="columnIndex === 0">
          <div
            class="table-row"
            style="font-size: 16px; color: #999999; line-height: 50px"
          >
            +
          </div>
          <el-input
            v-model="searchText"
            placeholder="搜索项目名称或拼音缩写"
            class="search-input_1_1"
            style="width: 100%"
            clearable
            @input="handleSearch"
            @focus="showSearchKeyboard"
            @click.stop
          />

          <!-- 搜索全键盘 -->
          <div
            v-if="
              searchKeyboardVisible &&
              props.displayNowUUid == detailUUid &&
              props.displayNowUUid3 == props.displayNowUUid2
            "
            @click.stop
          >
            <!-- 数字行 (所有模式都显示) -->
            <!-- 键盘 -->
            <SearchKeyboard
              :mode="keyboardMode"
              @input="(result: any) => inputSearchChar(result)"
              @delete="deleteSearchChar()"
              @clear="clearSearch"
              @switch="switchKeyboard"
              v-if="searchKeyboardVisible"
            />
          </div>

          <!-- 搜索结果下拉列表 -->
          <div
            v-if="
              searchResults.length > 0 &&
              props.displayNowUUid == detailUUid &&
              props.displayNowUUid3 == props.displayNowUUid2
            "
            class="search-results"
            @click.stop
          >
            <div class="table-header">
              <div
                class="header-cell"
                style="width: 520px; text-align: left; padding-left: 16px"
              >
                药品
              </div>
              <div
                class="header-cell"
                style="width: 200px; text-align: left; padding-left: 16px"
              >
                规格
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                厂家
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                单价
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                单位
              </div>
            </div>
            <div
              v-for="result in searchResults"
              :key="result.projectId"
              class="search-result-item"
              @click="selectSearchResult(result)"
            >
              <div
                class="result-name"
                style="width: 520px; text-align: left; padding-left: 16px"
              >
                {{ result.drugName }}
              </div>
              <div
                class="result-category"
                style="width: 200px; text-align: left; padding-left: 16px"
              >
                {{ result.specification }}
              </div>
              <div
                class="result-spec"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                {{ result.mfrName }}
              </div>
              <div
                class="result-price"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                ¥ {{ (result.price / 100).toFixed(2) }}
              </div>
              <div
                class="result-price"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                {{ result.packUnitText }}
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { getDrugRxList } from '@/api/formwork';
import { calculateTotalDose } from '@/utils/rxUtil';
import stores from '@/store';
import AutocompleteMulti from '@/components/AutocompleteMulti.vue';
const useBaseDataStore = stores.useBaseDataStore();
const skinTestEnum = ref<any[]>(
  useBaseDataStore.getEnumSelect('skinTestEnum') || []
);
const searchKeyboardOnTop = ref(false);
const searchInputRef = ref<HTMLInputElement | null>(null);
// 定义数据类型
// interface any {
//   examId: number;
//   projectId: number; // 主键ID
//   projectName: string; // 项目名称;CT
//   price: number; // 价格
//   projectCategory: string; // 项目分类;1检查2.检验3.治疗 projectCategoryEnum
//   projectCategoryName: string; // 项目分类名称
//   projectType: string; // 项目类型;头部CT 如果projectCategory=1取字典中的EXAM_TYPE,projectCategory=2取LAB_TYPE，如果等于3取EXT_TYPE
//   sampleType: string; // 样本类型;如果是检验项目需要维护1.全血 sampleTypeEnum
//   chargeType: string; // 收费类型1项目2穴位 ProjectChargeTypeEnum
//   unit: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   unitName: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   isNew?: boolean;
//   remark?: string;
//   frequencyCode?: string; // 频率代码
//   frequencyName?: string; // 频率名称
// }

// 定义表头列类型
interface TableColumn {
  key: string;
  label: string;
  width?: string;
  flex?: boolean;
  align?: 'left' | 'center' | 'right';
}

// Props
interface Props {
  title?: string;
  tableData?: any;
  frequencyOptions?: Array<{ frequencyCode: string; frequencyName: string }>;
  defaultActiveType?: 'inspection' | 'examination';
  columns?: TableColumn[];
  displayNowUUid?: string;
  displayNowUUid3?: string;
  displayNowUUid2?: string;
  visitStatus?: string;
  recomScene?: string;
  isInitialLoad?: boolean;
}
const detailUUid = ref('');
const isInitialLoad = ref(true);
const props = withDefaults(defineProps<Props>(), {
  title: '查验项目',
  tableData: { detailList: [], cycle: 1, frequencyCode: '' },
  frequencyOptions: () => [],
  defaultActiveType: 'inspection',
  displayNowUUid: '',
  displayNowUUid3: '',
  displayNowUUid2: '',
  visitStatus: '1',
  recomScene: '',
  isInitialLoad: true,
  columns: () => [
    { key: 'index', label: '序号', width: '80px', align: 'center' },
    { key: 'drugName', label: '药品', width: '250px' },
    { key: 'skinTest', label: '皮试', width: '109px' },
    { key: 'drugCategory', label: '类型', width: '100px' },
    { key: 'period', label: '用量/次', width: '130px' },
    { key: 'totalCount', label: '总量', width: '100px' },
    { key: 'remark', label: '备注', flex: true },
  ],
});

// Emits
const emit = defineEmits<{
  'update:tableData': [value: any[]];
  'active-type-change': [type: 'inspection' | 'examination'];
  'row-update': [row: any, index: number];
  'search-result-select': [result: any];
  searchKeyboard: any;
  isInitial: any;
}>();

// 响应式数据
const activeType = ref<any>(props.defaultActiveType);
const searchText = ref('');
const searchKeyboardVisible = ref(false);
const keyboardMode = ref<'english' | 'chinese'>('english');
const searchResults = ref<any[]>([]);

// 数字键盘相关
const keyboardVisible = ref(false);
const currentEditRow = ref<any | null>(null);
const currentEditField = ref<any>(null);

// 获取列的样式
const getColumnStyle = (column: TableColumn) => {
  return {
    width: column.flex ? undefined : column.width,
    flex: column.flex ? 1 : undefined,
    textAlign: column.align || 'left',
    justifyContent: column.align ? 'center' : '',
  };
};
// 从传入的频率项中获取每天用药次数 frequencyTimes
const getTimesPerDay = (): number | null => {
  const code = props.tableData?.frequencyCode;
  if (!code) return null;
  const freqItem = (props.frequencyOptions || []).find(
    (f: any) => f.frequencyCode === code
  );
  const times = Number((freqItem as any)?.frequencyTimes);
  return isNaN(times) || times <= 0 ? null : times;
};
// 依据当前行、分组频率与周期，计算该行总量
const recalcRowTotal = (row: any) => {
  const dosageNum = Number(row?.dosage);
  const cycleNum = Number(props.tableData?.cycle);
  const timesPerDay = getTimesPerDay();
  console.log(row);

  if (
    isNaN(dosageNum) ||
    dosageNum <= 0 ||
    isNaN(cycleNum) ||
    cycleNum <= 0 ||
    timesPerDay == null
  ) {
    return;
  }
  const newTotal = calculateTotalDose(
    dosageNum,
    timesPerDay,
    cycleNum,
    row.isMinSplit,
    row.isSplit,
    row.minPackQty
  );
  if (row.totalOutQty !== newTotal) {
    row.totalOutQty = newTotal;
  }
};
// 将当前表格数据抛给父组件，由父组件写回 group.detailList
const emitUpdateAll = () => {
  isSyncing.value = true;
  emit('update:tableData', displayTableData.value);
  // 下一轮 tick 允许再次响应父级更新
  nextTick(() => {
    isSyncing.value = false;
  });
};

// 重新计算所有行
const recalcAllRows = () => {
  if (!Array.isArray(displayTableData.value)) return;
  displayTableData.value.forEach((r) => recalcRowTotal(r));
  // 重算后，同步给父组件
  emitUpdateAll();
};
const displayTableData = ref<any[]>([]);
// 避免子->父 emit 后父->子传回导致的循环
const isSyncing = ref(false);
// 仅在 detailList 引用变化时同步，避免深度监听导致的多次触发
watch(
  () => props.tableData?.detailList,
  (list) => {
    detailUUid.value = props.tableData.uuid;
    if (isSyncing.value || !Array.isArray(list)) return;
    displayTableData.value = list.map(
      (item: {
        drugDosageUnitText: any;
        minPackQty: string;
        minPackUnitText: string;
        packUnitText: string;
        drugDosage: any;
        projectCategory: string;
        skinTest: string;
        drugCategory: any;
      }) => ({
        ...item,
        specification:
          item.drugCategory == 3
            ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
            : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
        projectCategoryName: useBaseDataStore.getEnumData(
          item.projectCategory,
          'projectCategoryEnum'
        ),
        skinTestName: useBaseDataStore.getEnumData(
          item.skinTest,
          'skinTestEnum'
        ),
        drugCategoryName: useBaseDataStore.getEnumData(
          item.drugCategory,
          'drugCategoryEnum'
        ),
      })
    );
  },
  { deep: true, immediate: true }
);
watch(
  () => props.isInitialLoad,
  (newVal) => {
    console.log(newVal);
    
    isInitialLoad.value = newVal;
  },
  { deep: true,immediate: true }
);

// 方法
const setActiveType = (type: 'inspection' | 'examination') => {
  activeType.value = type;
  emit('active-type-change', type);
};
const onchangeAutocom = (row: { remark: any }, index: number, item: any) => {
  row.remark = item;
  emit('row-update', row, index);
};
const updateRow = (row: any, index: number) => {
  console.log(row);
  emit('row-update', row, index);
};
// 深度差异比较函数
function getDeepChanges(newObj: any[], oldObj: any[], path = '') {
  if (!oldObj) return [{ path, newValue: newObj }];

  if (Array.isArray(newObj)) {
    const changes: any[] = [];
    newObj.forEach((item, index) => {
      changes.push(...getDeepChanges(item, oldObj[index], `${path}[${index}]`));
    });
    return changes;
  }

  return newObj !== oldObj
    ? [{ path, oldValue: oldObj, newValue: newObj }]
    : [];
}
function extractDifferences(changeItems: any[]) {
  // 深度比较两个值是否相等
  function isDeepEqual(
    a: { [x: string]: any } | null,
    b: { [x: string]: any } | null
  ) {
    if (a === b) return true;
    if (
      typeof a !== 'object' ||
      a === null ||
      typeof b !== 'object' ||
      b === null
    )
      return false;

    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;

    for (const key of keysA) {
      if (!keysB.includes(key)) return false;
      if (!isDeepEqual(a[key], b[key])) return false;
    }
    return true;
  }

  return changeItems
    .map((item) => {
      const { path, oldValue, newValue } = item;
      const uuid = newValue?.uuid || oldValue?.uuid; // 获取UUID

      const changedFields: any = {};

      // 收集所有key，包括oldValue和newValue中的
      const allKeys = new Set([
        ...Object.keys(oldValue || {}),
        ...Object.keys(newValue || {}),
      ]);

      // 比较每个字段
      for (const key of allKeys) {
        const oldVal = oldValue?.[key];
        const newVal = newValue?.[key];
        // 只有当值确实不同时才记录
        if (!isDeepEqual(oldVal, newVal)) {
          changedFields[key] = {
            old: oldVal,
            new: newVal,
            uuid: uuid,
          };
        }
      }

      // 只返回有实际变化的项
      return Object.keys(changedFields).length > 0
        ? { path, changes: changedFields, uuid }
        : null;
    })
    .filter(Boolean); // 过滤掉没有实际变化的项
}
// ==================== 自动计算总量（总出库量）开始 ====================
// 监听：行内 dosage 变化时，重算对应行（或全部行）
watch(
  () =>
    (Array.isArray(displayTableData.value) ? displayTableData.value : []).map(
      (r: any) => ({
        d: r.dosage,
        s: r.frequencyTimes,
        uuid: r.uuid,
        c: r.cycle,
      })
    ),
  (nval, cval) => {
    //console.log(nval);
    //console.log(cval);
    //console.log(getDeepChanges(nval, cval));
    // 使用示例
    if (isInitialLoad.value) {
      isInitialLoad.value = false;
      emit('isInitial', false);
      return;
    }
    const diffs = extractDifferences(getDeepChanges(nval, cval));
    //console.log('实际变化的字段:', diffs);

    // 获取所有变化的UUID
    const changedUUIDs = diffs.map((diff: any) => diff.uuid).filter(Boolean);

    // 先补全 totalOutQty
    if (displayTableData.value.length === 0) {
      return;
    }
    console.log(displayTableData.value);

    // 对匹配的行进行处理
    for (const row of displayTableData.value || []) {
      if (
        currentEditField.value !== 'totalOutQty' &&
        changedUUIDs.includes(row.uuid)
      ) {
        //console.log('需要重新计算的行:', row);
        recalcRowTotal(row);
      }
    }

    // 重算后同步给父组件
    emitUpdateAll();
    // // 再汇总价格
    // recalcTotalAmount();
  },
  { deep: true }
);
// ==================== 自动计算总量（总出库量）结束 ====================

// 获取单位名称的方法
const getUnitName = (unitCode: string) => {
  const UNITDATA = useBaseDataStore.getDictsSelect('UNIT') || [];
  // 过滤出unitType等于2的数据
  const filteredUnits = UNITDATA.filter(
    (unit: any) => unit.unitType === '2' || unit.unitType === 2
  );
  // 根据unitCode查找对应的单位名称
  const foundUnit = filteredUnits.find(
    (unit: any) => unit.unitCode === unitCode
  );
  //console.log(foundUnit);

  return foundUnit ? foundUnit.unitText : unitCode; // 如果找不到就返回原始unitCode
};

// 搜索方法
// 搜索方法
const handleSearch = async (value: string) => {
  //console.log('搜索内容:', value);

  // 模拟搜索结果数据

  const result = await getDrugRxList({
    drugName: value,
    drugCategory: '1',
    recoms: props.recomScene,
  });
  console.log(result);
  searchResults.value =
    result?.data.map((item: any) => ({
      ...item,
      drugCategoryName: useBaseDataStore.getEnumData(
        item.drugCategory,
        'drugCategoryEnum'
      ),
      specification:
        item.drugCategory == 3
          ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
          : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
      usageCode: item?.usageList?.[0]?.usageCode || '',
      usageCodeText: '',
      frequencyCode: '',
      frequencyCodeText: '',
      dosage: null,
      dosageUnit: '',
      mfrName: useBaseDataStore.getMfrName(item.mfrId),
      dosageUnitText: item.drugDosageUnitText,
      cycle: '',
      skinTest: '1',
      cycleUnit: '',
      cycleUnitText: '',
      totalOutQty: null,
      totalOutQtyUnit: '',
      totalOutQtyUnitText: item.packUnitText,
      isSplit: item.isSplit,
      minPackUnitText: item.minPackUnitText,
    })) || [];
};

// 搜索键盘相关方法
const showSearchKeyboard = () => {
  searchKeyboardVisible.value = true;
  emit('searchKeyboard');
  keyboardVisible.value = false;
  document.addEventListener('keydown', handleKeyboardShortcut);
  handleSearch(searchText.value);
};

const hideSearchKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (
      target.closest('.search-keyboard') ||
      target.closest('.search-results') ||
      target.closest('.search-input_1_1')
    ) {
      return;
    }
  }

  searchKeyboardVisible.value = false;
  document.removeEventListener('keydown', handleKeyboardShortcut);
};

const handleKeyboardShortcut = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.shiftKey && event.key === 'T') {
    event.preventDefault();
    switchKeyboard();
  } else if (event.key === 'Escape') {
    event.preventDefault();
    hideSearchKeyboard();
  }
};

const inputSearchChar = (char: string) => {
  searchText.value += char;
  handleSearch(searchText.value);
};

const deleteSearchChar = () => {
  if (searchText.value.length > 0) {
    searchText.value = searchText.value.slice(0, -1);
    handleSearch(searchText.value);
  }
};

const clearSearch = () => {
  searchText.value = '';
  searchResults.value = [];
};

const switchKeyboard = () => {
  if (keyboardMode.value === 'english') {
    keyboardMode.value = 'chinese';
  } else if (keyboardMode.value === 'chinese') {
    keyboardMode.value = 'english';
  }
};
const querySearchAsync = (queryString: string, cb: any) => {
  const data1 = useBaseDataStore.getDictsSelect('REMARK') || [];
  // 仅保留 rxType 为 5 的项（兼容数字/字符串）
  const filtered = (Array.isArray(data1) ? data1 : []).filter(
    (item: any) => item?.rxType === 5 || item?.rxType === '2'
  );
  const results = filtered.map((item: any) => ({
    value: item.remarkText,
    ...item,
  }));
  cb(results);
};
const selectSearchResult = (result: any) => {
  //console.log('选择了:', result);
  // 将搜索结果转换为 any 格式
  const newItem: any = {
    ...result,
    examId: Date.now(),
    name: result.projectName,
    category: activeType.value === 'inspection' ? '检验' : '检查',
    frequency: '',
    dosage: null,
    cycle: 1,
    totalOutQty: null,
    projectId: result.projectId,
    drugName: result.projectName,
    price: result.price,
    skinTest: '1',
    projectCategory: result.projectCategory,
    projectCategoryName: result.projectCategoryName,
    projectType: result.projectType,
    sampleType: result.sampleType,
    chargeType: result.chargeType,
    unit: result.unit,
    unitName: result.unitName,
    remark: result.instrs,
  };

  // 通过 emit 更新父组件的数据
  // const updatedData = [...displayTableData.value, newItem];
  // emit('update:tableData', updatedData);

  // ElMessage.success(`已选择: ${result.projectName}`);
  searchKeyboardVisible.value = false;
  searchResults.value = [];
  searchText.value = '';
  result.remark = result.instrs;
  emit('search-result-select', result);
};

// 数字键盘相关方法
const showKeyboard = (row: any, index: number, field: any) => {
  currentEditRow.value = row;
  currentEditField.value = field;
  keyboardVisible.value = true;
  searchKeyboardVisible.value = false;
  // 确保字段有初始值
  if (row[field] === undefined || row[field] === null) {
    row[field] = null;
    //console.log('showKeyboard: initialized field value to 1', field);
  }
};

const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.number-keyboard')) {
      return;
    }
  }
  keyboardVisible.value = false;
  currentEditRow.value = null;
  currentEditField.value = null;
};

const inputNumber = (num: string, type?: string) => {
  console.log('键盘输入值:', num, '类型:', type);
  if (type) {
    // 直接设置数值（来自NumberDecimal组件）
    currentEditRow.value[currentEditField.value] = Number(num);
  }

  // 有效性检查
  if (!currentEditRow.value || !currentEditField.value) {
    return;
  }

  // 获取当前值和字段配置
  const field = currentEditField.value;
  const currentValue = currentEditRow.value[field];
  const isDecimalField = ['dosage', 'splitPrice'].includes(field); // 假设这些字段允许小数

  // 处理小数点输入
  if (num === '.') {
    // if (!isDecimalField) {
    //   //console.log('小数点输入被拒绝，该字段不支持小数');
    //   return;
    // }

    // 如果当前值已经是小数或包含小数点，不再添加
    const currentStr = currentValue?.toString() || '';
    if (currentStr.includes('.')) {
      return;
    }

    // 添加小数点
    currentEditRow.value[field] = currentStr + '.';
    return;
  }

  // 处理数字输入
  let newValue: number | string;

  // 初始化或处理现有值
  if (currentValue === undefined || currentValue === null) {
    newValue =
      isDecimalField && currentEditRow.value[field]?.toString().includes('.')
        ? '0.' + num
        : num;
  } else {
    const currentStr = currentValue.toString();

    if (isDecimalField && currentStr.includes('.')) {
      // 小数部分拼接
      const [integer, decimal] = currentStr.split('.');
      newValue = `${integer}.${decimal}${num}`;
    } else {
      // 整数部分拼接
      newValue = currentStr === '0' ? num : currentStr + num;
    }
  }

  // 转换为数字并验证范围
  const numericValue = Number(newValue);
  const maxValue = 999; // 根据字段获取最大值

  if (numericValue <= maxValue) {
    currentEditRow.value[field] = isDecimalField
      ? numericValue
      : Math.floor(numericValue);
  } else {
  }
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) {
    //console.log('deleteNumber: currentEditRow or currentEditField is null');
    return;
  }

  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    //console.log('deleteNumber: current value is undefined/null');
    return;
  }

  const currentValueStr = currentValue.toString();
  const newValue = currentValueStr.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
};

const confirmAdd = (row: any, index: number) => {
  if (!row.projectName.trim()) {
    ElMessage.warning('请选择项目');
    return;
  }

  // const newItem: any = {
  //   id: Date.now(),
  //   name: row.name,
  //   category: activeType.value === 'inspection' ? '检验' : '检查',
  //   frequency: row.frequency,
  //   period: row.period,
  //   totalCount: row.totalCount,
  //   remark: row.remark || '新添加项目',
  // };

  // const updatedData = [...props.tableData, newItem];
  // emit('update:tableData', updatedData);
  // ElMessage.success('项目添加成功');
};

// 删除行方法
const deleteRow = (row: any, index: number) => {
  displayTableData.value = displayTableData.value.filter(
    (item) => item.uuid !== row.uuid
  );
  emit('update:tableData', displayTableData.value);
  ElMessage.success('项目删除成功');
};

// 生命周期钩子
onMounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
    hideSearchKeyboard(event);
  };
  document.addEventListener('mousedown', globalClickHandler);
});

onUnmounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
    hideSearchKeyboard(event);
  };
  document.removeEventListener('mousedown', globalClickHandler);
});
defineExpose({
  displayTableData,
});
</script>

<style lang="scss" scoped>
// 自定义表格样式
.custom-table {
  width: 100%;
  border-radius: 6px;
  overflow: visible;
  border-radius: 12px 12px 12px 12px;
  position: relative;
  background: #ffffff;
  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 16px 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .action-buttons {
      display: flex;
      align-items: center;
      .el-button.active {
        background-color: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }

  .table-header {
    display: flex;
    background-color: #f8f8f8;
    border-bottom: 1px solid #e4e7ed;

    .header-cell {
      padding: 12px 8px;
      text-align: center;
      font-weight: 600;
      color: #909399;
      font-size: 14px;
      border-right: none;
      align-items: center;
    }
  }

  .table-row-container {
    position: relative;
    display: flex;
    align-items: center;

    &:hover {
      .delete-button {
        opacity: 1;
        visibility: visible;
      }
    }

    .table-row {
      flex: 1;
      display: flex;
      border-bottom: 1px solid #e4e7ed;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f5f7fa;
      }

      &.add-row {
        background-color: #fafafa;
      }

      .table-cell {
        padding: 12px 8px;
        border-right: none;
        height: 50px;
        position: relative;
        display: flex;
        align-items: center;
        &:last-child {
          justify-content: flex-start;
          padding-left: 12px;
        }

        &:has(.number-keyboard) {
          overflow: visible;
          z-index: 1;
        }
      }
    }

    .delete-button {
      position: absolute;
      right: -18px;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #989898;
      border-radius: 50%;
      cursor: pointer;
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s ease;
      z-index: 10;

      &:hover {
        transform: translateY(-50%) scale(1.1);
      }

      img {
        width: 16px;
        height: 16px;
        filter: brightness(0) invert(1); // 将图标变为白色
      }
    }
  }

  .table-row {
    display: flex;
  }
}

// 无边框输入框样式
:deep(.borderless-select) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.borderless-input) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.no-border-input) {
  .el-input__wrapper {
    box-shadow: none;
    padding: 0;
  }
}

// 数字键盘样式
.number-keyboard {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 9999 !important;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
  margin-top: 4px;
  transform: translateZ(0);

  .keyboard-row {
    display: flex;
    gap: 4px;
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    width: 50px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      width: 104px;
      background: #f56c6c;
      color: white;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}

// 搜索行样式
.search-row {
  .table-cell {
    border-right: none;

    &:first-child {
      padding-left: 17px;
      display: flex;
      width: 100%;
      height: 50px;
    }
  }

  .search-input_1_1 {
    :deep(.el-input__wrapper) {
      background-color: transparent;
      box-shadow: none;
      border-radius: 4px;
    }

    :deep(.el-input__inner) {
      font-weight: 500;

      &::placeholder {
        font-weight: normal;
      }
    }

    :deep(.el-input__prefix) {
      color: #f87171;
    }
  }
}

// 搜索键盘样式
.search-keyboard {
  position: absolute;
  top: -250px;
  left: 0;
  z-index: 9999;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
  width: 600px;
  max-width: 90vw;

  .keyboard-row {
    display: flex;
    gap: 6px;
    margin-bottom: 8px;
    justify-content: center;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    min-width: 45px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #ffffff;
    color: #333;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8px;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.clear-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.switch-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.space-btn {
      min-width: 60px;
      color: rgb(0, 0, 0);
    }
  }
}

// 搜索结果样式
.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9998;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  margin-top: 4px;
  max-height: 300px;
  overflow-y: auto;
  width: 100%;

  // 重写搜索结果中的表头样式，确保与内容对齐
  .table-header {
    .header-cell {
      text-align: left !important;
      justify-content: flex-start !important;
    }
  }

  .search-result-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f5f7fa;
    cursor: pointer;
    text-align: left;
    transition: background-color 0.2s;
    height: 48px; // 设置固定高度

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: #f0f9ff;
    }

    // 清除子元素样式，使用内联样式控制
    .result-name,
    .result-category,
    .result-spec,
    .result-price {
      display: flex;
      align-items: center;
      height: 100%;
      font-size: 14px;
      color: #333;
    }

    .result-category,
    .result-spec {
      font-size: 12px;
      color: #333;
    }

    // .result-price 空规则移除
  }
}
</style>
